<?php
require_once __DIR__ . '/../vendor/autoload.php';
require __DIR__ . "/../src/config/Loadfile.php";

$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER["REQUEST_URI"];

// 基于正则表达式匹配动态路由
// 匹配 /user/数字 形式的路由
require_once ROOT_PATH . "/config/Container.php";

$container = new AppContainer();
$container->initRoute();
$router = $container->router;

$match_result = $router->match($method, $uri);

error_log("-----------------");
error_log("method: {$method}, uri: {$uri}");
error_log("match_result:  " . json_encode($match_result));
error_log("-----------------");

if ($match_result && is_array($match_result)) {
        $controller = $match_result["controller"];
        $action = $match_result["action"];
        $params = null;
        if (isset($match_result["params"])) {
                $params = array_slice($match_result["params"], offset: 1);
        }
        // 判断$controller->$action是否有参数
        if (is_object($controller) && method_exists($controller, $action)) {
                try {
                        if (is_array($params)) {
                                $controller->$action(...$params);
                        } else {
                                $controller->$action();
                        }
                } catch (Exception $e) {
                        $controller->error($e->getMessage());
                }
        } else {
                http_response_code(500);
                echo "500 Internal Server Error";
        }
} else {
        http_response_code(404);
        echo "404 Not Found";
}

?>